<style scoped>
    .codesql {
    font-size: 11pt;
    font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
  }
</style>
<template>
    <div id='myApp'>
        <Row style="margin-bottom: 10px;border-bottom: 1px solid #eeeeee;">
            <Col span="5" style="border-bottom:2px solid #2d8cf0 ;padding: 0 0 8px 18px;">
            <span style="color: #2d8cf0;">
                <Icon type="md-add-circle" />&nbsp;&nbsp;
                <span style="color: black;">数据管理&nbsp;&nbsp;>&nbsp;&nbsp;</span>
                SQL查询
            </span>
            </Col>
        </Row>
        <Row style="margin-bottom: 10px;">
            <Col span="16" offset="4">
                <Col span="6">
                SQL编辑器：
                </Col>
                <Col span="6" offset="12">
                <a style="float: right;">SQL帮助文档>></a>
                </Col>
                <Input disabled style="visibility: hidden; height: 0;"></Input>
                <div style="border: 1px solid #ccc;">
                    <codemirror
                      ref="myCm"
                      v-model="formItems.sql"
                      :options="cmOptions"
                      class="code">
                    </codemirror>
                </div>
                
            </Col>
            
        </Row>
        <Row style="margin-bottom: 10px;">
            <Col span="16" offset="4">
            <Col span="8">
            <Checkbox :disabled="true" v-model="limitstatus"></Checkbox>限制结果数量为&nbsp;<InputNumber type="number" v-model="autoLimit" :max="1000" :min="1" style="width: 20%;"></InputNumber>&nbsp;条
            </Col>
            <Col span="12" offset="4">
            <div style="float: right;">               
                <Button type="primary" @click="executeSql()">执行</Button>
                <Button type="primary" @click="modal1=true" style="margin-right: 15px;">保存</Button>
                <Button type="success" @click="addApi">发布API</Button>
                <Button type="success" @click="dataExploration()" :disabled = 'this.dataExplorShow'>数据探索</Button>
            </div>
            <Modal v-model="modal1" width="700">
                <p slot="header" style="color: #2d8cf0;">
                    <Icon type="ios-information-circle"></Icon>
                    <span>保存SQL任务</span>
                </p>
                <div style="text-align:center">
                    <Form ref="formValidate" :rules="ruleValidate" :model="formItems" :label-width="150">
                        <FormItem prop="sqlName" label="SQL任务名称：">
                            <Input v-model="formItems.sqlName" />
                        </FormItem>
                        <FormItem prop="withAPI" label="是否生成API：">
                            <div style="text-align: left;">
                                <i-switch v-model="formItems.withAPI" @on-change="changestatus" />
                            </div>
                        </FormItem>
                        <FormItem prop="sql" label="SQL语句：">
                                <Input type="textarea" :autosize="{minRows: 10,maxRows: 25}" v-model="formItems.sql" />
                        </FormItem>
                    </Form>
                </div>
                <div slot="footer">
                    <Button type="primary" @click="saveSql">保存</Button>
                </div>
            </Modal>
            </Col>
            </Col>
        </Row>
        <template v-if="sqlstatus==true">
            <Row style="padding-top:20px;margin-bottom: 10px;">
                <Col span="16" offset="4">
                <Col span="6">
                SQL执行结果：
                </Col>
                <Col span="6" offset="12">
                    <div style="float: right;cursor: pointer;">
                    <Button style="margin-bottom: 10px;" @click="exportData()">
                        导出<Icon type="md-download"></Icon>
                    </Button>                      
                        <Tooltip content="全屏显示" placement="bottom-end">
                            <Icon type="ios-expand" size="30" @click="openFull" />
                        </Tooltip>
                    </div>
                </Col>
                <Table border :loading="loading" :columns="sqlColumns" :data="sqlQueryDataLast"></Table>
                {{dataCount}}条结果，执行时间{{countTime}}ms
                </Col>
            </Row>
        </template>
        <template v-else>            
            <Row>
                <Col span="16" offset="4">
                    <div class="errortext">{{errorText}}</div>
                </Col>
            </Row>
        </template>
        <Modal v-model="datastatus" fullscreen footer-hide title="SQL执行结果：">
            <Row style="margin-bottom: 20px;">
                <Col span="12">
                <!-- 每页显示:
                <Input style="width: 60%;" v-model="pageSize" />&nbsp;条 -->
	             <Page :total="dataCount"
	             size="small"
	             @on-change="changepage"
	             @on-page-size-change="pages"
	             show-total
	             show-sizer />
                </Col>
                <!-- <Col span="6">
                    <div style="float: right;">
                        分隔符:
                        <Input style="width: 65%;" value='/t' />
                    </div>
                </Col>
                <Col span="6">
                    搜索:
                    <Input style="width: 55%;" />
                    <Button type="text" style="color: #2d8cf0;">过滤</Button>
                </Col> -->
                <Col span="10" offset="2">
                    <div style="float: right;">
                        <Button type="text" @click="openRows" style="color: #2d8cf0;">
                            展示/隐藏列
                            </Button>
                    </div>
                </Col>
            </Row>
            <Table border :loading="loading" :columns="sqlColumns" :data="sqlQueryData"></Table>
            
        </Modal>
        <Modal v-model="rowstatus" title="展示/隐藏列"
        @on-ok="resetColumns"
        >
            <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
            </div>
            <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange">
                <Checkbox v-for="(item,index) in checkAllData" :label="item" :key="index"></Checkbox>
            </CheckboxGroup>
        </Modal>

    </div>
</template>
<script>
import zmitiUtil from '../../lib/util'
import { mapState, mapActions } from 'vuex'
import { codemirror } from 'vue-codemirror'
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");

    export default {
        computed: {
        	countTime(){
        		/*查询结果所花的时间*/
        		return this.responseTime-this.requestsTime
        	},
            codemirror() {
                return this.$refs.myCm.codemirror
            },
        	...mapState({
           		Authorization: state => state.Authorization,
                sqlstr:state => state.sqlstr
        	})
        },
        components:{
            codemirror
        },
        watch:{
            curCode(newVal,oldVal){
                console.log(newVal,'newVal')
                console.log(oldVal,'oldVal')
            }
        },
        data() {
            return {
                code:'',
                autoLimit:10,
                limitstatus:true,//开启限制条数
                modal1: false,
                loading:false,
                ajaxHistoryData: [],
                dataCount: 0,
                pageSize: 10,
                xia: 0,
                datastatus:false,//是否全屏
                rowstatus:false,//显示隐藏列
                checkAllGroup: [],//已选择的列
                checkAllData:[],//全部列
                historyColumns: [
                    {
                        title: '编号',
                        key: 'num',
                        width:100,
                        align: 'center'
                    },
                    {
                        title: 'SQL任务名称',
                        key: 'taskName',
                        align: 'center'
                    },
                    {
                        title: '是否生成API',
                        key: 'api',
                        width:140,
                        align: 'center'
                    },
                    {
                        title: '最近修改时间',
                        key: 'modifyTime',
                        align: 'center'
                    }
                ],
                ruleForm: {
                    id: '',
                    name: '',

                },
                formItems:{
                    sqlName:'',
                    withAPI:false,
                    sql:''
                },
                ruleValidate: {
                    sqlName: [
                        { required: true, message: '任务名称不能为空', trigger: 'blur' }
                    ],
                    sql: [
                        { required: true, message: 'SQL语句不能为空', trigger: 'blur' }
                    ]
                },
                editor:'',
                sqlQueryDataLast:[],//前5条数据
                sqlQueryData:[],//表格中的全部条数
                initTableData:[],//第几页的数据
                allTableData:[],//分页用的全部数据
                sqlColumns:[],
                sqlstatus:false,
                errorText:'',
                requestsTime:0,
                responseTime:0,
                condition:{
                	pageNO:0,
                	pageSize:10
                },
                curCode:'',
                cmOptions:{
                    value:'',
                    mode: 'text/x-mariadb',
                    indentWithTabs: true,
                    smartIndent: true,
                    lineNumbers: true,
                    matchBrackets: true,
                    extraKeys: {'Ctrl': 'autocomplete'},//自定义快捷键
                    hintOptions: {//自定义提示选项
                        tables: {
                          users: ['name', 'score', 'birthDate'],
                          countries: ['name', 'population', 'size']
                        }
                    }
                },
                dataExplorShow: true
            }
        },
        mounted() {
            this.formItems.sql=this.sqlstr;
            console.log(this.sqlstr,'store中的sql语句');
            setTimeout(()=>{

            },300)
        },
        methods: {
            changeCode(value){
                this.code = value;       
                //this.editor.setValue(this.code);
            },
            changestatus(status){//是否生成API
                this.formItems.withAPI=status;                
                console.log(status,'status');
            },            
            changepage(index) {// 到第几页
                var _this = this;
                //index当前页码
                console.log('index = ' + index)
                //第1页索引为0
                _this.condition.pageNO=index-1;
                _this.sqlQueryData=_this.initTableData[_this.condition.pageNO];
            },
            pages(num) { //每页显示多少条数
            	var _this = this;
            	_this.initTableData=[];//清空分页里的数据
                _this.condition.pageSize = num;
                _this.condition.pageNO=0;
                _this.loading=true;
                for(var i=0;i<_this.allTableData.length;i+=_this.condition.pageSize){
					let iNum=Number(i+_this.condition.pageSize)
				    _this.initTableData.push(_this.allTableData.slice(i,iNum));
				}
				console.log(_this.initTableData,'按照新的条件分页后的全部数据');
				
                setTimeout(()=>{
                	_this.loading=false;
                    _this.sqlQueryData=_this.initTableData[0];//第1页内容
                },300)            
            },
            testsql(){
                console.log(this.formItems.sql,'testsql语句')
            },
            executeSql(){//查询sql               
                let _this = this;
                var path='sql/run';
                console.log(this.formItems.sql.split("\n").join(""),'查询的sql语句')
                /*过滤换行符并用空格隔开*/
                let formItemsSql=this.formItems.sql//.split('\n').join('');
                var postData = {//参数
                    query:formItemsSql,
                    autoLimit:_this.autoLimit
                }
                _this.loading=true;
                _this.requestsTime=Number(new Date());//提交时的时间
                /*先清空内容，以免push后重复显示*/
                _this.sqlQueryDataLast=[];
                _this.sqlColumns=[];
                _this.checkAllGroup=[];
                _this.initTableData=[];
                _this.allTableData=[];
                zmitiUtil.Ajax(path,postData).then(res => {
                    var data = res.data; 
                    console.log(data,'获取数据源') 
                    _this.responseTime=Number(new Date());//返回时的时间
                    console.log(_this.requestsTime,_this.responseTime,'两个时间');
                    //_this.formItems.sql;
                    _this.loading=false;
                    if(!data.attemptedAutoLimit){
                        _this.errorText=data.result;
                        this.dataExplorShow = true;//控制数据探索按钮
                    } else {                        
                        _this.sqlstatus=true;
                        /*获取全部*/                   
                        //_this.sqlQueryData=data.rows;
                        _this.dataCount=data.rows.length;//总条数
                        _this.allTableData=data.rows;//用于分页的全部数据
                        /*let pageNumber=Number(_this.condition.pageSize);
						for(var i=0;i<data.rows.length;i+=pageNumber){
							let iNum=Number(i+pageNumber)
						    _this.initTableData.push(data.rows.slice(i,iNum));
						}*/

						for(var i=0;i<data.rows.length;i+=_this.condition.pageSize){
							let iNum=Number(i+_this.condition.pageSize)
						    _this.initTableData.push(data.rows.slice(i,iNum));
						}

						console.log(_this.initTableData,'分页后的全部数据');
						_this.sqlQueryData=_this.initTableData[0];//第1页内容
                        /*获取前5条*/
                        data.rows.forEach((item,index)=>{
                            if(index<5){
                                _this.sqlQueryDataLast.push(item);
                            }                            
                        })
                        _this.dataCount=data.rows.length;

                        /*通过rows第1行数据遍历出各单元格名称*/
                        let rows=data.rows[0];//第1行数据
                        //console.log(rows,'rows');

                        for ( let i in rows){
                        	/*设置表格单元格*/
                            _this.sqlColumns.push({
                                title: i,
                                key: i,
                                align: 'center',
                                minWidth:80,
                                maxWidth:150,
                                tooltip:true//超出部分显示为省略号，并用 Tooltip 组件显示完整内容
                            })

                            _this.checkAllData.push(i);//将单元格属性名称追加至选择列表之中
                        }
                        console.log(_this.sqlColumns,'_this.sqlColumns');
                        console.log(_this.checkAllData,'_this.checkAllData');
                        
                        //默认勾选全部单元格并显示
                        this.checkAllGroup = this.checkAllData;    
                        this.dataExplorShow = false;//控制数据探索按钮                   
                    }
                }).catch((error) => {
                    console.log(error,'error');
                });
            },
            saveSql(){//保存SQL任务
                let _this = this;
                var path='sql/save';
                var postData = _this.formItems;
                _this.$refs['formValidate'].validate((valid) => {
                    if (valid) {
                        zmitiUtil.Ajax(path,postData).then(res => {
                            var data = res.data; 
                            console.log(data,'获取数据源');
                            if (data.code==1) {                        
                                _this.$Message.success('保存成功!');
                                _this.modal1=false;
                            }else{
                                _this.$Message.error(data.result);
                            }
                        }).catch((error) => {
                            console.log(error,'error');
                        });
                    }
                })
            },
            openFull(){//打开全屏
                var _this = this;
                _this.datastatus=true;
            },
            openRows(){//展示隐藏选择单元格
                this.rowstatus=true;
            },

            checkAllGroupChange (data) {//选择需要显示的单元格
                var _this = this;
                console.log(data,'已选择的列');
                _this.checkAllGroup=data;
            },
            resetColumns(rows){//重新设置各单元格
                var _this = this;
                let checkColumns=[];
                _this.checkAllGroup.map((item,index)=>{
                    checkColumns.push({
                        title: item,
                        key: item,
                        align: 'center',
                        minWidth:80,
                        maxWidth:150,
                        tooltip:true
                    })
                })
                console.log(checkColumns,'checkColumns');
                _this.sqlColumns=checkColumns;
            },
            addApi(){//执行成功后前往发布API页面,并附带sql语句
                this.$router.push('/postAPI');
                this.$store.state.sqlstr=this.formItems.sql;
            },
            dataExploration(){
                if(this.dataExplorShow){
                  return;
                }
                this.$router.push('/dataExplore');
            },
            exportData(){
                var path = 'sql/export_excel'
                
                zmitiUtil.AjaxExport(path).then(res =>  {
  console.log(res)
  const link = document.createElement('a')
  let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
  link.style.display = 'none'
  link.href = URL.createObjectURL(blob);
  let num = ''
  for(let i=0;i < 10;i++){
   num += Math.ceil(Math.random() * 10)
  }
  link.setAttribute('download', num + '.xlsx')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  }).catch((error) => {
                    console.log(error,'error');
                }); 
            }

        }
    }
</script>